﻿using System;
using System.Collections.Generic;

using YunSpace.Data;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using YunSpace.Domain.ViewModel.WeChat.Site;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Repository.SiteMgr;
using YunSpace.Domain.IRepository.SiteMgr;

namespace YunSpace.Application.WeChat
{

    /// <summary>
    /// 需求类处理发布需求-预定-个人
    /// </summary>
    public class DemandApp
    {
        private readonly ISiteClientsProjectByDemandRepository scpDemand = new SiteClientsProjectByDemandRepository();
        private readonly UserApp userApp = new UserApp();

        public List<ClientOrderViewModel> Get()
        {
            var sql = @"SELECT a.F_FullName, sco.F_Id,sco.F_Id orderId, 
		                        sco.F_DemandId, 
                                sco.F_WorkFormId,
		                        sco.F_FlowUserId, 
		                        sco.F_OrderState, 
		                        sco.F_OrderStateProcess, 
		                        sco.F_CreatorTime, 
		                        sco.F_LastModifyTime, 
                                sco.F_SignOut,
		                        scp.F_Source, 
		                        scp.F_ActivityTheme, 
		                        scp.F_ActivityType, 
		                        scp.F_DemandCash, 
		                        scp.F_ActivityStartDate, 
		                        scp.F_ActivityEndDate, 
		                        scp.F_ActivityCityId, 
		                        scp.F_SiteType, 
		                        scp.F_SiteArea, 
		                        scp.F_Mating, 
		                        scp.F_Intention, 
		                        scp.F_Note, 
		                        scp.F_State,                                 
		                        atype.F_ActivityTypeName, 
		                        su.F_RealName as 'F_FlowUserName', 
                                scpc.F_Contact, 
		                        sc.F_ClientName 
                            FROM Site_Client_Order sco
                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scp.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            LEFT JOIN Sys_Area AS a ON a.F_Id = scp.F_ActivityCityId
                            WHERE sco.F_State=1 AND scp.F_State=1 AND sco.F_OrderEnvironment = 1  ORDER BY sco.F_CreatorTime desc; ";
            //--AND sco.F_OrderState = 5 
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<ClientOrderViewModel>(sql);
                return result;
            }
        }


        /// <summary>
        /// 获取所有预订信息
        /// </summary>
        /// <param name="wxUserId">手机号</param>
        /// <param name="isContainCommented">是否包含已经评论过</param>
        /// <returns></returns>
        public List<ReserveDto> GetAllReserveDtos(string wxUserId, bool isContainCommented = true)
        {
            var user = userApp.GetUserByWxUserId(wxUserId);
            var phoneFilterSql = "";

            if (user?.F_Phone != null)
            {
                phoneFilterSql = $"scpc.F_Phone = '{user.F_Phone}' OR";
            }

            var containCommentedFilterSql = "";

            if (!isContainCommented)
            {
                containCommentedFilterSql = "AND wcc.F_Id IS NULL";
            }

            var sql = $@"SELECT DISTINCT scp.F_Id AS DemandId ,
                                scp.F_State AS DemandState ,
                                scp.F_CreatorTime AS DemandCreateTime ,
                                sco.F_Id AS OrderId ,
                                sco.F_OrderState AS OrderState ,
                                sco.F_CreatorTime AS OrderCreateTime,
                                sco.F_LastModifyTime AS OrderLastTime,
                                sco.F_State AS OrderValidState ,
                                scp.F_ActivityTheme AS ActivityTheme ,
                                scp.F_ActivityStartDate AS ActivityStartDate ,
                                scp.F_ActivityEndDate AS ActivityEndDate ,
                                scp.F_ActivityCityId AS ActivityCityId ,
                                scp.F_PersionNumber AS PersionNumber ,
                                scp.F_SiteArea AS SiteArea,
                                scp.F_DemandCash AS DemandCash,
                                sco.F_OrderEnvironment AS OrderEnvironment,
                                sco.F_WorkFormId AS F_WorkFormId,
                                scp.F_Intention,
                                ( CASE WHEN wcc.F_Id IS NULL THEN false
                                       ELSE true
                                  END ) AS IsCommented
                        FROM    Site_Clients_ProjectByDemand scp
                                LEFT JOIN Site_Client_Order sco ON sco.F_DemandId = scp.F_Id
                                LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                                LEFT JOIN ( SELECT  sid.F_ItemCode AS 'F_ActivityType' ,
                                                    sid.F_ItemName AS 'F_ActivityTypeName'
                                            FROM    Sys_Items si
                                                    INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
                                                                                      AND si.F_EnCode = 'ActivityType'
                                          ) atype ON scp.F_ActivityType = atype.F_ActivityType
                                LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                                LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                                LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                                LEFT JOIN WeChat_Comment wcc ON wcc.F_OrderId = sco.F_Id
                        WHERE   1=1 AND ({phoneFilterSql} scp.F_WxUserId = '{wxUserId}' )
                                {containCommentedFilterSql}
                        ORDER BY scp.F_CreatorTime DESC;";

            using (var db = new RepositoryBase())
            {
                var result = db.FindList<ReserveDto>(sql);
                return result;
            }
        }

        /// <summary>
        /// 获取预订信息详情
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        //public List<ReserveDto> GetDetailDtos(string Id)
        //{

        //}

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>

        public SiteClientsProjectByDemandEntity GetForm(string keyValue)
        {
            return scpDemand.FindEntity(keyValue);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue"></param>
        public void DeleteForm(string keyValue)
        {
            scpDemand.Delete(t => t.F_Id == keyValue);
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="settingEntity"></param>
        /// <param name="keyValue"></param>
        public string SubmitForm(SiteClientsProjectByDemandEntity demandEntity, string keyValue)
        {
            int result = 0;
            var id = "";
            if (!string.IsNullOrEmpty(keyValue))
            {
                id = keyValue;
                demandEntity.Modify(keyValue);
                result = scpDemand.Update(demandEntity);
            }
            else
            {
                demandEntity.Create();
                id = demandEntity.F_Id;
                result = scpDemand.Insert(demandEntity);
            }
            if (result > 0)
            {
                return id;
            }
            else
            {
                return "";
            }


        }


    }
}
